/**
* 
*/
var Site = {
    /*
    * @param {object|string} tab/url
    * @param {string}
    * @description callback {object} {price, date}
    * */
    'getPageInfo': function (param) {
        console.log(6666666666);
        //param: tab/url
        var confKey = param.confKey;
        console.log(1)
        console.log(confKey);
        console.log(2)
        if (param.tab) {
            // 从已经打开的 tab 分析信息
            var tab = param.tab;
            if (!confKey)
                confKey = Site.url2key(null, param.tab.url);
            if (!confKey) {
                return null;
            }
            chrome.tabs.executeScript(tab.id, {
                'file': 'js/lib/jquery-1.7.1.min.js'
            }, function () {
                chrome.tabs.executeScript(tab.id, {
                    file: 'js/lib/jquery.tmpl.min.js'
                },
                    function () {
                        chrome.tabs.executeScript(tab.id, {
                            'code': Site.config[confKey].finderStr //回调是 msgType == 'pageInfo' 的消息
                        }, function () {
                            chrome.tabs.sendRequest(tab.id, { msgType: 'getPageInfo' }, function (response) {
                                if (typeof param.success == 'function') {
                                    response.conf = Site.config[confKey];
                                    response.date = new Date(response.date);
                                    response.url = tab.url;
                                    param.success(response);
                                }
                            });
                        });
                    });
            });
        } else if (param.url) {
            var conf;
            if (!confKey) {
                conf = Site.url2key(null, param.url);
                confKey = conf.key;
            }

            if (!confKey) {
                return null;
            }
            this.ajax({
                url: param.url,
                success: function (xhr) {
                    var response = {
                        response: xhr.responseText,
                        url: param.url,
                        id: param.id,
                        confKey: param.confKey
                    };

                    console.log(confKey);
                    var _info = Site.config[confKey]._getPageInfo('str')(response);
                    _info.url = param.url;
                    if (typeof param.success == 'function') {
                        _info.conf = Site.config[confKey];
                        _info.date = new Date(_info.date);
                        param.success(_info);
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log(textStatus);
                }
            });
        }
    },
    /*
    * @param {string|null=}
    * @param {string}
    * */
    'url2key': function (domain, url) {
        var that = this;
        if (arguments.length == 1) {
            url = domain;
            domain = null;
        }
        for (var key in that.config) {
            var keyid = that.config[key].urlReg(url);
            if (keyid) {
                return keyid;
            }
            //                return {
            //                    key: key,
            //                    id: id
            //                };
        }
        return null;
    },
    'ajax': function (param) {
        if (!param || !param.url)
            return false;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                param.success(this);
            }
        };
        xhr.open(param.type || 'GET', param.url, false);
        xhr.send();
    },
    'config': {}, //'360buy.com'
    'storage': {},
    'handle': {
        /*
        * @description 更新存储的数据里与某个 url 相关的数据
        * @param {string} url
        * @param {object} data {price:number, date: number, conf, url}
        * */
        'updateSiteData': function (url, data) {
            exports.work.addPrice(data.conf.key, data);
        }
    },
    'constants': {
        product: {
            '360buy.com': {
                'newPrice': {
                    xpath: '.book_detailed li span',
                    regexp: "price:'([0-9.]+)'"
                },
                'name': {
                    xpath: '#name',
                    regexp: ""
                },
                'stock': {
                    xpath: '#storeinfo .i-storeinfo',
                    regexp: ''
                },
                'coupon': {
                    xpath: '#cx',
                    regexp: ''
                },
                'gift': {
                    xpath: '#i-largess',
                    regexp: ''
                },
                'buyUrl': {
                    xpath: '#InitCartUrl',
                    regexp: ''
                },
                'imgUrl': {
                    xpath: '#spec-n1>img',
                    regexp: ''
                },
                'assistBarPosition': {
                    xpath: 'a[clstag*=jiangjia]',
                    after: true,
                    remove: true
                },
                'urlReg': ['http://www.360buy.com/product/([0-9]+).html', 'http://mvd.360buy.com/([0-9]+).html'],
                'unionUrlTmpl': 'http://click.union.360buy.com/JdClick/?unionId=5990&t=4&to={{url}}'
            },
            'tmall.com': {
                'newPrice': {
                    xpath: 'em.tb-promo-price-type+strong',
                    xpath2: '#J_StrPrice',
                    regexp: ''
                },
                'name': {
                    xpath: '.tb-detail-hd>h3',
                    regexp: ""
                },
                'stock': {
                    xpath: '#storeinfo .i-storeinfo',
                    regexp: ''
                },
                'coupon': {
                    xpath: '#cx',
                    regexp: ''
                },
                'gift': {
                    xpath: '#i-largess',
                    regexp: ''
                },
                'buyUrl': {
                    xpath: '#InitCartUrl',
                    regexp: ''
                },
                'imgUrl': {
                    xpath: '#J_ImgBooth',
                    regexp: ''
                },
                'assistBarPosition': {
                    xpath: '#J_StrPriceModBox>.yuan',
                    after: true,
                    remove: false
                },
                'urlReg': ['http://detail.tmall.com/.*[?&]{1}id=([0-9]*).*',
                'http://detail.tmall.com/.*[?&]{1}spu_id=([0-9]*).*',
                'http://item.tmall.com/.*[?&]{1}id=([0-9]*).*'],
                'unionUrlTmpl': '{{url}}'
            },
            'amazon.cn': {
                'newPrice': {
                    xpath: '#actualPriceValue>.priceLargex',
                    regexp: '<b class="priceLarge">￥ ([0-9,.]*)</b>'
                },
                'name': {
                    xpath: '#btAsinTitle',
                    regexp: ""
                },
                'stock': {
                    xpath: '#storeinfo .i-storeinfo',
                    regexp: ''
                },
                'coupon': {
                    xpath: '#cx',
                    regexp: ''
                },
                'gift': {
                    xpath: '#i-largess',
                    regexp: ''
                },
                'buyUrl': {
                    xpath: '#InitCartUrl',
                    regexp: ''
                },
                'imgUrl': {
                    xpath: '#original-main-image',
                    regexp: ''
                },
                'assistBarPosition': {
                    xpath: '#actualPriceValue',
                    after: true,
                    remove: false
                },
                'urlReg': ['http://www.amazon.cn/[.]*[gp/|dp/]*product/([a-zA-Z0-9]*)[.]*',
                'http://www.amazon.cn/[a-zA-Z0-9\-\/%\u4e00-\u9fa5]*dp/([a-zA-Z0-9]*)[.]*'],
                'unionUrlTmpl': '{{url}}'
            },
            'dangdang.com': {
                'newPrice': {
                    xpath: '.promotions>.promotions_price_d>b',
                    xpath2: '',
                    regexp: 'id="salePriceTag">￥([0-9,.]+)</span>'
                },
                'name': {
                    xpath: '.dp_main>.h1_title>h1',
                    regexp: ''
                },
                'stock': {
                    xpath: '',
                    regexp: ''
                },
                'coupon': {
                    xpath: '',
                    regexp: ''
                },
                'gift': {
                    xpath: '',
                    regexp: ''
                },
                'buyUrl': {
                    xpath: '#InitCartUrl',
                    regexp: ''
                },
                'imgUrl': {
                    xpath: '#largePic',
                    regexp: ''
                },
                'assistBarPosition': {
                    xpath: '.info>.price_d',
                    after: true,
                    remove: false
                },
                'urlReg': ['http://product.dangdang.com/product.aspx.*[?&]{1}product_id=([0-9]*).*'], //http://product.dangdang.com/product.aspx?product_id=1011175107
                'unionUrlTmpl': '{{url}}'
            },
            'yihaodian.com': {
                'newPrice': {
                    xpath: '#productFacadePrice',
                    xpath2: '#nonMemberPrice>strong',
                    regexp: ''
                },
                'name': {
                    xpath: '#productMainName',
                    regexp: ''
                },
                'stock': {
                    xpath: '',
                    regexp: ''
                },
                'coupon': {
                    xpath: '',
                    regexp: ''
                },
                'gift': {
                    xpath: '',
                    regexp: ''
                },
                'buyUrl': {
                    xpath: '',
                    regexp: ''
                },
                'imgUrl': {
                    xpath: '#productImg',
                    regexp: ''
                },
                'assistBarPosition': {
                    xpath: '#btnNotice2',
                    after: true,
                    remove: true
                },
                'urlReg': ['http://www.yihaodian.com/product.*/([0-9-]*).*'], //http://www.yihaodian.com/product/1845671_2
                'unionUrlTmpl': '{{url}}'
            },
            '51buy.com': {
                'newPrice': {
                    xpath: 'strong.price_font',
                    xpath2: '',
                    regexp: ''
                },
                'name': {
                    xpath: 'div.property>h1:eq(0)',
                    regexp: ''
                },
                'stock': {
                    xpath: '',
                    regexp: ''
                },
                'coupon': {
                    xpath: '',
                    regexp: ''
                },
                'gift': {
                    xpath: '',
                    regexp: ''
                },
                'buyUrl': {
                    xpath: '',
                    regexp: ''
                },
                'imgUrl': {
                    xpath: '#smallImage',
                    regexp: ''
                },
                'imgAlternate': {
                    url: 'img/51buy_product.png'
                },
                'assistBarPosition': {
                    xpath: 'strong.price_font',
                    after: true,
                    remove: false
                },
                'urlReg': ['http://item.51buy.com/item-([0-9]*).*.html'], //http://item.51buy.com/item-322488.html
                'unionUrlTmpl': '{{url}}'
            }
        }
    }
};

//导入网站配置数据
(function (site) {
    if (typeof _SiteModel == 'undefined') {
        _SiteModel = {};
    }
    site.config = {};
    //360buy

    $.each(site.constants.product, function(key, value){
        (function (_key) {
        site.storage[_key] = {};
        site.config[_key] = {
            'key': _key,
            'getPageInfo': function (param) {
                site.getPageInfo(param);
            },
            '_getPageInfo': function (type) {
                //if (!dom)//字符串全文匹配跳过
                //    dom = document;

                if (type == 'str') {
                    return function (response) {
                        var str = response.response;
                        var url = response.url;
                        var constant = site.constants.product[_key];
                        
                        var price = $(str).find(constant.newPrice.xpath).text().trim();
                        if(!price || price == ''){
                            if(constant.newPrice.xpath2){
                                price = $(str).find(constant.newPrice.xpath2).text().trim();
                            }
                            if(!price || price == ''){
                                var reg = new RegExp(constant.newPrice.regexp, "i");
                                var priceArr = str.match(reg);
                                if (priceArr && priceArr.length == 2) {
                                    price = priceArr[1];
                                } else {
                                    price = -1;
                                }
                            }
                        }

                        function getCommentsNum(c) {
                            var num = 0;
                            if (c) {
                                var nums = c.match(/\(([0-9.]+)\)/);
                                if (nums && nums.length == 2) {
                                    num = nums[1];
                                }
                            }
                            console.log(num);
                            return num;
                        }

                        var name = $(str).find(constant.name.xpath).text();
                        var stock = $(str).find(constant.stock.xpath).text();
                        var coupon = $(str).find(constant.coupon.xpath).text();
                        var gift = $(str).find(constant.gift.xpath).html();
                        var reviews = getCommentsNum($('#cnum0').text());
                        var reviewAsGood = getCommentsNum($(str).find('#cnum1').text());
                        var reviewAsAvg = getCommentsNum($(str).find('#cnum2').text());
                        var reviewAsBad = getCommentsNum($(str).find('#cnum3').text());
                        var buyUrl = $(str).find(constant.buyUrl.xpath).attr('href');
                        var imgUrl = constant.imgAlternate ? chrome.extension.getURL(constant.imgAlternate.url) : $(str).find(constant.imgUrl.xpath).attr('src');
                        var data = {
                            'id': response.id,
                            'url': url,
                            'newPrice': (price || '').replace(',', ''),
                            'date': new Date(),
                            'name': name,
                            'stock': stock,
                            'coupon': coupon,
                            gift: gift,
                            'reviews': {
                                total: reviews,
                                good: reviewAsGood,
                                avg: reviewAsAvg,
                                bad: reviewAsBad
                            },
                            'buyUrl': buyUrl,
                            imgUrl: imgUrl,
                            noticeSettings: {
                                coupon: { enabled: 'checked', param: '' },
                                cheapest: { enabled: 'checked', param: '' },
                                reduction: { enabled: '', param: '' },
                                onSale: { enabled: '', param: '' },
                                notes: ''
                            }
                        };
                        return data;
                    };
                } else if (type == 'tab') {
                    return function () {
                        var constant = site.constants.product[_key];
                        if (typeof tabContentListener === 'undefined') {
                            tabContentListener = true;
                            chrome.extension.onRequest.addListener(function (request, sender, sendResponse) {
                                var url = document.location.href;
                                console.log(7);
                                if (request.msgType == 'getPageInfo') {
                                    //request.data
                                    var p, price;
                                    for (var i = document.scripts ? (document.scripts.length - 1) : -1; i >= 0; i--) {
                                        if (document.scripts[i].innerHTML.indexOf('京东价：￥') > 0) {
                                            price = document.scripts[i].innerHTML.match(/京东价：￥([0-9.]+)。感/);
                                            if (price && price.length == 2) {
                                                price = price[1];
                                                break;
                                            }
                                        }
                                    }
                                    if (i == -1) {
                                        price = -1;
                                    }
                                    console.log('price geted');
                                    function getCommentsNum(c) {
                                        var num = 0;
                                        if (c) {
                                            var nums = c.match(/\(([0-9.]+)\)/);
                                            if (nums && nums.length == 2) {
                                                num = nums[1];
                                            }
                                        }
                                        console.log(num);
                                        return num;
                                    }
                                    var name = $(constant.name.xpath).text();
                                    console.log(name);
                                    var stock = $(constant.stock.xpath).text();
                                    var coupon = $(constant.coupon.xpath).html();
                                    var gift = $('#i-largess').html();
                                    var reviews = getCommentsNum($('#cnum0').text());
                                    var reviewAsGood = getCommentsNum($('#cnum1').text());
                                    var reviewAsAvg = getCommentsNum($('#cnum2').text());
                                    var reviewAsBad = getCommentsNum($('#cnum3').text());

                                    console.log('z');
                                    var buyUrl = $(constant.buyUrl.xpath).attr('href');
                                    var imgUrl = $(constant.imgUrl.xpath).attr('src');
                                    var data = {
                                        'id': '',
                                        'url': url,
                                        'newPrice': price,
                                        'date': new Date(),
                                        'name': name,
                                        'stock': stock,
                                        'coupon': coupon,
                                        gift: gift,
                                        'reviews': {
                                            total: reviews,
                                            good: reviewAsGood,
                                            avg: reviewAsAvg,
                                            bad: reviewAsBad
                                        },
                                        'buyUrl': buyUrl,
                                        imgUrl: imgUrl,
                                        noticeSettings: {
                                            coupon: { enabled: 'checked', param: '' },
                                            cheapest: { enabled: 'checked', param: '' },
                                            reduction: { enabled: '', param: '' },
                                            onSale: { enabled: '', param: '' },
                                            notes: ''
                                        }
                                    };
                                    console.log('data geted');
                                    console.log(JSON.stringify(data));
                                    sendResponse(data);
                                }
                            });
                        }
                    };
                }
            },
            'urlReg': function (url) {
                var constant = site.constants.product[_key];
                var reg = constant.urlReg;
                try
                {
                    for(var i=0; i < reg.length; i++)
                    {
                        var r = url.match(new RegExp(reg[i], "i"));
                        if (r && r.length == 2) {
                        //alert(r[1]);
                            return {
                                key: _key,
                                id: r[1]
                            };
                        }
                    }
                }
                catch(e)
                {
                    console.log(e);
                    throw e;
                }
               
                return null;
            }

        };

        site.config[_key].finderStr = '(' + site.config[_key]._getPageInfo('tab').toString() + ')()';

    })(key);
    });

})(Site);
/*
  
   "page_action": {
    "default_icon": "img/logo.png", 
    "default_title": "点击管理历史价格",    
    "default_popup": "pageaction.html"
  },
  */